package com.chuzhiyun.chengguoxy.feature.internship.leave;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.GridLayoutManager;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chuzhiyun.chengguoxy.R;
import com.chuzhiyun.chengguoxy.databinding.ActivityLeaveHomeBinding;
import com.chuzhiyun.chengguoxy.databinding.ActivityLeaveInfoBinding;
import com.chuzhiyun.chengguoxy.feature.base.BaseActivity;
import com.chuzhiyun.chengguoxy.feature.bean.LeavedaysoffInfoBean;
import com.chuzhiyun.chengguoxy.feature.bean.WorkTagsImageBean;
import com.chuzhiyun.chengguoxy.network.NetApi;
import com.chuzhiyun.chengguoxy.network.NetService;
import com.chuzhiyun.chengguoxy.network.StringNetCallback;
import com.chuzhiyun.chengguoxy.utlis.CustomClickListener;
import com.chuzhiyun.chengguoxy.utlis.GlideUtils;
import com.chuzhiyun.chengguoxy.utlis.NewItemClickListener;
import com.chuzhiyun.chengguoxy.utlis.NewOnItemChildClickListener;
import com.chuzhiyun.chengguoxy.utlis.PictureSelectUtil;
import com.chuzhiyun.chengguoxy.utlis.StringUtils;
import com.chuzhiyun.chengguoxy.utlis.TimeUtils;
import com.chuzhiyun.chengguoxy.utlis.ToastCustom;
import com.codingending.popuplayout.PopupLayout;
import com.google.gson.Gson;
import com.haibin.calendarview.Calendar;
import com.haibin.calendarview.CalendarView;
import com.shehuan.nicedialog.BaseNiceDialog;
import com.shehuan.nicedialog.NiceDialog;
import com.shehuan.nicedialog.ViewConvertListener;
import com.shehuan.nicedialog.ViewHolder;
import com.vondear.rxtool.RxFileTool;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@SuppressWarnings({"FieldCanBeLocal", "FieldMayBeFinal"})
public class LeaveInfoActivity extends BaseActivity<ActivityLeaveInfoBinding> {

    private Integer leaveId = 0;
    private List<WorkTagsImageBean> datas = new ArrayList<>();
    private LeaveInfoActivity.MyAdapter myAdapter;
    private String leaveStartDate;
    private String leaveEndDate;
    private String reason;
    private String chooseTimeDate;
    private Boolean isChange = false;
    private List<String>deleteFile = new ArrayList<>();
    private String approval;


    final @SuppressLint("SimpleDateFormat")
    SimpleDateFormat dateFormat  = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    public void initView(View view) {
        viewBinding.navView.ivBack.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                onBackPressed();
            }
        });

        viewBinding.navView.tvTitle.setText("请假");

        initEditLength(viewBinding.editLiyou,viewBinding.tvLengthTip,200);
        viewBinding.editLiyou.setFocusableInTouchMode(false);

        viewBinding.recyclerView.setLayoutManager(new GridLayoutManager(mContext, 4));
        myAdapter = new MyAdapter(R.layout.item_worktags_input, datas,isChange);
        viewBinding.recyclerView.setAdapter(myAdapter);
        myAdapter.addChildClickViewIds(R.id.delete_Img);
        myAdapter.notifyDataSetChanged();

        myAdapter.setOnItemClickListener(new NewItemClickListener() {
            @Override
            protected void onSingleClick(BaseQuickAdapter adapter, View view, int position) {
                if (isChange){
                    WorkTagsImageBean bean = datas.get(position);
                    if (bean.getTagsType().equals("0"))
                    {
                        getPhoto((FragmentActivity) mContext);
                    }
                }
            }
        });

        myAdapter.setOnItemChildClickListener(new NewOnItemChildClickListener() {
            @Override
            protected void onSingleClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.delete_Img) {
                    if (isChange){
                        WorkTagsImageBean bean = datas.get(position);
                        if (bean.getTagsType().equals("1")||bean.getTagsType().equals("2"))
                        {
                            deleteFile.add(bean.getImageId()+"");
                            datas.remove(position);
                            deleteImageList();
                            myAdapter.notifyDataSetChanged();
                        }
                    }
                }
            }
        });

        viewBinding.tvStartTimeRl.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                if (isChange){
                    showBottomTimeChoose("1");
                }
            }

        });

        viewBinding.tvEndTimeRl.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                if (isChange){
                    showBottomTimeChoose("2");
                }
            }

        });

        viewBinding.editLiyou.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                reason = s.toString();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        viewBinding.tvSubmit.setOnClickListener(new CustomClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            protected void onSingleClick() {
                if (!isChange){
                    isChange = true;
                    viewBinding.tvSubmit.setText("重新提交");
                    viewBinding.editLiyou.setFocusableInTouchMode(true);
                    myAdapter.setNewChange(isChange);
                    myAdapter.notifyDataSetChanged();
                }
                else {
                    submitClick();
                }
            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private void submitClick() {

        if (StringUtils.isBlank(reason)) {
            ToastCustom.showErrorToast("请输入请假理由");
            return;
        }
        String url = NetApi.putLeavedaysoff(leaveId + "");
        HashMap<String, String> param = new HashMap<>();
        param.put("reason", reason);
        param.put("start", leaveStartDate);
        param.put("end", leaveEndDate);

        ArrayList<File> pictures = new ArrayList<>();
        if (datas.size() > 1) {
            for (int i = 0; i < datas.size(); i++) {
                WorkTagsImageBean imageBran = datas.get(i);
                if (imageBran.getTagsType().equals("1")) {
                    pictures.add(imageBran.getImageFile());
                }
            }
        }
        showLoadingDialog();
        NetService.getInstance().putFileWithParam(url, param, pictures, deleteFile, new StringNetCallback() {
            @Override
            public void onSuccess(String response, int statusCode) throws Exception {
                dismissLoadingDialog();
                if (statusCode==200){
                    ToastCustom.showSuccessToast("修改成功");
                    onBackPressed();
                }
            }

            @Override
            public void onError(String error) {
                System.out.println(error);
            }
        });
    }

    @Override
    public void initData() {

    }

    @Override
    public void setListener() {
        leaveId = getIntent().getIntExtra("leaveId",0);
        approval = getIntent().getStringExtra("approval");
        getLeaveDetalInfo();

        if (approval.equals("rejected"))
        {
            viewBinding.rlSubmit.setVisibility(View.GONE);
        }
        if (approval.equals("pending")||approval.equals("approved"))
        {
            viewBinding.rlSubmit.setVisibility(View.VISIBLE);
            viewBinding.tvStartTimeRl.setOnClickListener(new CustomClickListener() {
                @Override
                protected void onSingleClick() {
                    if (isChange)
                    {
                        //时间选择器
                        showBottomTimeChoose("1");
                    }
                }

            });

            viewBinding.tvEndTimeRl.setOnClickListener(new CustomClickListener() {
                @Override
                protected void onSingleClick() {
                    if (isChange)
                    {
                        showBottomTimeChoose("2");
                    }
                }

            });

            viewBinding.editLiyou.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    reason = s.toString();
                }

                @Override
                public void afterTextChanged(Editable s) {

                }
            });


        }
    }

    private void getLeaveDetalInfo(){
        String url = NetApi.getLeavedaysoffInfo(leaveId+"");
        NetService.getInstance().get(url, new StringNetCallback() {
            @Override
            public void onSuccess(String response, int statusCode) throws Exception {
                System.out.println(response);
                if (statusCode==200){
                    Gson gson = new Gson();
                    LeavedaysoffInfoBean bean = gson.fromJson(response,LeavedaysoffInfoBean.class);
                    leaveStartDate = bean.getStart();
                    leaveEndDate = bean.getEnd();
                    reason = bean.getReason();

                    if (bean.getFiles()!=null)
                    {
                        if (bean.getFiles().size()!=0)
                        {
                            WorkTagsImageBean bean1 = new WorkTagsImageBean();
                            bean1.setTagsType("0");
                            datas.add(bean1);
                            for (int i=0;i<bean.getFiles().size();i++)
                            {
                                LeavedaysoffInfoBean.FilesBean filesBean = bean.getFiles().get(i);
                                String urls = filesBean.getFile();
                                WorkTagsImageBean bean2 = new WorkTagsImageBean();
                                bean2.setTagsType("2");
                                bean2.setImageUrl(urls);
                                bean2.setImageId(filesBean.getId());
                                datas.add(bean2);
                            }
                            changeImageList();
                            //noinspection deprecation
                            myAdapter.setNewData(datas);
                            myAdapter.notifyDataSetChanged();
                        }
                        else
                        {
                            WorkTagsImageBean bean2 = new WorkTagsImageBean();
                            bean2.setTagsType("0");
                            datas.add(bean2);
                            myAdapter.notifyDataSetChanged();
                        }

                    }
                    else
                    {
                        WorkTagsImageBean bean2 = new WorkTagsImageBean();
                        bean2.setTagsType("0");
                        datas.add(bean2);
                        myAdapter.notifyDataSetChanged();
                    }

                    viewBinding.tvStartTime.setText(leaveStartDate);
                    viewBinding.tvEndTime.setText(leaveEndDate);
                    viewBinding.editLiyou.setText(reason);
                }
            }

            @Override
            public void onError(String error) {
                System.out.println(error);
            }
        });
    }

    private void getPhoto(FragmentActivity myActivity) {

        NiceDialog.init()
                .setLayoutId(R.layout.dialog_head_img)
                .setConvertListener(new ViewConvertListener() {
                    @Override
                    public void convertView(ViewHolder holder, final BaseNiceDialog dialog) {
                        holder.setOnClickListener(R.id.select_photo_dialog_btn_camera, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                                takePhotoCamera();
                            }
                        });
                        holder.setOnClickListener(R.id.select_photo_dialog_btn_album, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                                takePhotoAlbum();
                            }
                        });
                        holder.setOnClickListener(R.id.select_photo_dialog_btn_cancel, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                            }
                        });
                    }
                })
                .setGravity(Gravity.BOTTOM)
                .show(myActivity.getSupportFragmentManager());
    }

    private void takePhotoCamera() {
        PictureSelectUtil.with(this)
                .camera()
                .setCallback(new PictureSelectUtil.OnCallback() {
                    @Override
                    public void onCallback(Uri uri) {
                        File mFile = RxFileTool.getFilePhotoFromUri((FragmentActivity) mContext,uri);
                        WorkTagsImageBean bean = new WorkTagsImageBean();
                        bean.setImageFile(mFile);
                        bean.setTagsType("1");
                        datas.add(bean);
                        changeImageList();
                        myAdapter.notifyDataSetChanged();
                    }
                }).select();
    }

    private void takePhotoAlbum(){
        PictureSelectUtil.with(this)
                .gallery()
                .setCallback(new PictureSelectUtil.OnCallback() {
                    @Override
                    public void onCallback(Uri uri) {
                        File mFile = RxFileTool.getFilePhotoFromUri((FragmentActivity) mContext,uri);
                        WorkTagsImageBean bean = new WorkTagsImageBean();
                        bean.setImageFile(mFile);
                        bean.setTagsType("1");
                        datas.add(bean);
                        changeImageList();
                        myAdapter.notifyDataSetChanged();
                    }
                }).select();
    }

    private void changeImageList()
    {
        // 把name为haha的学生放在最后面
        WorkTagsImageBean temp = new WorkTagsImageBean();
        boolean flag = false;
        for(int i = 0; i < datas.size(); i++){
            WorkTagsImageBean student = datas.get(i);
            if (student.getTagsType().equals("0")) {
                temp = student;
                flag = true;
                datas.remove(i);
                break;
            }
        }
        if (flag) {
            if (datas.size()<4)
            {
                datas.add(temp);
            }
        }
    }

    private void deleteImageList()
    {
        boolean isFlag = false;
        for(int i = 0; i < datas.size(); i++){
            WorkTagsImageBean student = datas.get(i);
            if (student.getTagsType().equals("0")) {
                isFlag = true;
            }
        }
        if (!isFlag)
        {
            WorkTagsImageBean temp2 = new WorkTagsImageBean();
            temp2.setTagsType("0");
            datas.add(temp2);
        }
    }

    private void showBottomTimeChoose(String type){

        //时间选择器
        View view=View.inflate(mContext,R.layout.timechoose_menu,null);
        PopupLayout popupLayout = PopupLayout.init(mContext,view);
        popupLayout.show();

        chooseTimeDate = TimeUtils.getCurrentTime();

        TextView monthText = view.findViewById(R.id.month_Text);
        CalendarView calendarView = view.findViewById(R.id.calendarView);
        ImageView calendarLeft = view.findViewById(R.id.left_Text);
        ImageView calendarRight = view.findViewById(R.id.right_Text);
        calendarLeft.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                calendarView.scrollToPre();
            }

        });
        calendarRight.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                calendarView.scrollToNext();
            }

        });
        calendarView.setOnCalendarSelectListener(new CalendarView.OnCalendarSelectListener() {
            @Override
            public void onCalendarOutOfRange(Calendar calendar) {

            }

            @Override
            public void onCalendarSelect(Calendar calendar, boolean isClick) {
                String dateStr = null;
                try {
                    dateStr = TimeUtils.strToDateFormat(calendar.toString());
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                chooseTimeDate = dateStr;
            }
        });

        java.util.Calendar calendar = java.util.Calendar.getInstance();
        int y = calendar.get(java.util.Calendar.YEAR);
        int m = calendar.get(java.util.Calendar.MONTH);

        @SuppressLint("SimpleDateFormat") SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月");
        calendar.setTime(new Date());
        String monthString = df.format(calendar.getTime());
        monthText.setText(monthString);
        calendarView.setOnMonthChangeListener(new CalendarView.OnMonthChangeListener() {
            @SuppressLint("DefaultLocale")
            @Override
            public void onMonthChange(int year, int month) {
                if (month<10)
                {
                    monthText.setText(String.format("%d年0%d月", year, month));
                }
                else
                {
                    monthText.setText(String.format("%d年%d月", year, month));
                }
            }
        });

        TextView cancelText = view.findViewById(R.id.cancel_Text);
        TextView sureText = view.findViewById(R.id.sure_Text);
        cancelText.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                popupLayout.dismiss();
            }
        });

        sureText.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                popupLayout.dismiss();
                if (type.equals("1")){
                    if (!StringUtils.isBlank(chooseTimeDate)){
                        viewBinding.tvStartTime.setText(chooseTimeDate);
                        leaveStartDate = chooseTimeDate;
                    }
                }
                if (type.equals("2")){
                    if (!StringUtils.isBlank(chooseTimeDate)){
                        viewBinding.tvEndTime.setText(chooseTimeDate);
                        leaveEndDate = chooseTimeDate;
                    }
                }
            }

        });
    }

    public static class MyAdapter extends BaseQuickAdapter<WorkTagsImageBean, BaseViewHolder> {
        boolean isChange;
        public MyAdapter(int layoutResId, List<WorkTagsImageBean> data,boolean isChange) {
            super(layoutResId, data);
            this.isChange = isChange;
        }
        @Override
        protected void convert(@NotNull BaseViewHolder helper, WorkTagsImageBean item) {

            if (item.getTagsType().equals("0")){
                helper.setImageResource(R.id.tags_Img,R.mipmap.add_work);
                helper.setVisible(R.id.delete_Img,false);
            }
            if (item.getTagsType().equals("1"))
            {
                Bitmap bitmap= BitmapFactory.decodeFile(item.getImageFile().toString());
                helper.setImageBitmap(R.id.tags_Img,bitmap);
                if (isChange){
                    helper.setVisible(R.id.delete_Img,true);
                }
                else {
                    helper.setGone(R.id.delete_Img,true);
                }
            }
            if (item.getTagsType().equals("2"))
            {
                GlideUtils.getInstance().loadImage(getContext(), item.getImageUrl(), (ImageView) helper.getView(R.id.tags_Img));
                if (isChange){
                    helper.setVisible(R.id.delete_Img,true);
                }
                else {
                    helper.setGone(R.id.delete_Img,true);
                }
            }
        }
        public void setNewChange(boolean change) {
            isChange = change;
        }
    }

    @Override
    protected ActivityLeaveInfoBinding getViewBinding() {
        return ActivityLeaveInfoBinding.inflate(getLayoutInflater(), baseBinding.getRoot(), true);
    }
}